//
//  NewsDataBaseManager.m
//  ToYourHeartNews
//
//  Created by XJing on 16/1/29.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "NewsDataBaseManager.h"

@implementation NewsDataBaseManager
//创建数据库
+(NewsDataBaseManager *)shareInstance
{
    //静态指针 创建数据库
    static NewsDataBaseManager *dbManager = nil;
    
    if (!dbManager) {
        dbManager = [[NewsDataBaseManager alloc]init];
    }
    return dbManager;
    
}
///打开数据库
-(void)openDB
{
    //数据库一般放在Document下 后缀:db/sqlite
    //根据人名创建数据库
    NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
    NSString *pathStr = [str stringByAppendingString:@"newsDataBase.db"];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:pathStr];
    //直接创建数据库
//    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"newsDataBase.db"];
    //语句  创建数据库文件
    //参数1: 数据库路径(转换成UTF8)
    //参数2: 数据库指针地址
    int result = sqlite3_open(path.UTF8String, &dbNewsPoint);
    NSLog(@"打开数据库: %d, 路径: %@", result, path);
}
///关闭数据库
-(void)closeDB
{
    sqlite3_close(dbNewsPoint);
}
///创建表
-(void)createTable
{
    //1.SQL语句
    NSString *createSQL = @"create table if not exists news (newsName text, newsDate text, newsAuther_name text, newsWeburl text, newsType text, newsPk text, newsId integer PRIMARY KEY AUTOINCREMENT)";
    //2.执行语句
    //参数1: 数据库指针
    //参数2: sql语句
    //其他参数:NULL
    int result = sqlite3_exec(dbNewsPoint, createSQL.UTF8String, NULL, NULL, NULL);
    //判断
    [self judgeResult:result message:@"创建表"];
}
///删除表
-(void)dropTable
{
    //1.SQL语句
    NSString *dropSQL = @"drop table news";
    //执行
    int result = sqlite3_exec(dbNewsPoint, dropSQL.UTF8String, NULL, NULL, NULL);
    //判断
    [self judgeResult:result message:@"删除表"];
}
///增
-(void)insertNews:(AllDetailModel *)m
{
    //SQL
    NSString *insertSQL = [NSString stringWithFormat:@"insert into news (newsName, newsDate, newsAuther_name, newsWeburl, newsType, newsPk) values('%@', '%@', '%@', '%@', '%@', '%@')", m.title, m.date, m.auther_name, m.weburl, m.type, m.pk];
    //执行
    int result = sqlite3_exec(dbNewsPoint, insertSQL.UTF8String, NULL, NULL, NULL);
    //判断
    [self judgeResult:result message:@"插入"];
}
///删
-(void)deleteNewsWithId:(NSInteger)newsId
{
    NSString *deleteSQL = [NSString stringWithFormat:@"delete from news where newsId = '%ld'", newsId];
    int result = sqlite3_exec(dbNewsPoint, deleteSQL.UTF8String, NULL, NULL, NULL);
    [self judgeResult:result message:@"删除"];
}
///改
-(void)updateNews:(AllDetailModel *)newM withId:(NSInteger)NewsId
{
    NSString *updateSQL = [NSString stringWithFormat:@"update news set newsName = '%@', newsDate = '%@', newsAuther_name = '%@', newsWeburl = '%@', newsType = '%@', newsPk = '%@' where newsId = '%ld'", newM.title, newM.date, newM.auther_name, newM.weburl, newM.type, newM.pk, NewsId];
    int result = sqlite3_exec(dbNewsPoint, updateSQL.UTF8String, NULL, NULL, NULL);
    [self judgeResult:result message:@"更新数据"];
}
///查询
-(NSMutableArray *)select
{
    //查询后 数据处理过程
    //1.获取所有数据
    //2.先遍历行 得到每一行数据
    //3.再遍历当前行 每一列 按照对应关系保存在model中
    //4.model添加到数组 返回
    
    //SQL
    NSString *selectSQL = @"select *from news";
    //创建数据库替身
    sqlite3_stmt *stmt = nil;
    //SQL准备语句
    //把数据库对象/SQL语句/数据库替身 关联在一起
    int result = sqlite3_prepare_v2(dbNewsPoint, selectSQL.UTF8String, -1, &stmt, nil);
    //初始化返回的数组
    NSMutableArray *arr = [NSMutableArray array];
    //判断准备是否成功
    if (result == SQLITE_OK) {
        NSLog(@"查询准备成功");
        //遍历每一行数据
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            //逐行获取每一行信息
            const unsigned char *nNAme = sqlite3_column_text(stmt, 0);
            const unsigned char *nDate = sqlite3_column_text(stmt, 1);
            const unsigned char *nAuther_name = sqlite3_column_text(stmt, 2);
            const unsigned char *nWeburl = sqlite3_column_text(stmt, 3);
            const unsigned char *nType = sqlite3_column_text(stmt, 4);
            const unsigned char *nPk = sqlite3_column_text(stmt, 5);
            int nId = sqlite3_column_int(stmt, 6);
            //创建model对象
            AllDetailModel *m = [[AllDetailModel alloc]init];
            m.title = [NSString stringWithUTF8String:(const char *)nNAme];
            m.date = [NSString stringWithUTF8String:(const char *)nDate];
            m.auther_name = [NSString stringWithUTF8String:(const char *)nAuther_name];
            m.weburl= [NSString stringWithUTF8String:(const char *)nWeburl];
            m.type = [NSString stringWithUTF8String:(const char *)nType];
            m.pk = [NSString stringWithUTF8String:(const char *)nPk];
            m.NewsId = nId;
            
            [arr addObject:m];
        }
    }else{
        NSLog(@"失败: %d", result);
    }
    return arr;
}
///判断方法
-(void)judgeResult:(int)r message:(NSString *)mes
{
    if (r == SQLITE_OK) {
        NSLog(@"%@成功", mes);
    }else{
        NSLog(@"%@失败: %d", mes, r);
    }
}

@end
